package jsonparser;


import android.content.Context;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import javabean.SearchJson;
import timor.timor.R;

/**
 * Created by aaa on 15-4-28.
 */
public class JsonParser {
    private static ArrayList<SearchJson> list;

    public static void searchJsonParser( String path, final Context context, final ListView listView) {

        HttpUtils http = new HttpUtils();

        http.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                list=new ArrayList<SearchJson>();
                String json = objectResponseInfo.result;
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray array = jsonObject.getJSONArray("result");
                    for (int i = 0; i < array.length(); i++) {
                        SearchJson searchJson = new SearchJson();
                        JSONArray array1 = array.getJSONArray(i);
                        String s0 = (String) array1.get(0);
                        String s1 = (String) array1.get(1);
                        searchJson.setName(s0);
                        searchJson.setNumble(s1);

                        list.add(searchJson);
                    }
                    ArrayList<HashMap<String, String>> maps = new ArrayList<>();
                    if (list!=null){
                        for (int i = 0; i <list.size() ; i++) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("name",list.get(i).getName());
                            map.put("number",list.get(i).getNumble()+"条");
                            maps.add(map);
                        }
                    }
                    SimpleAdapter adapter=new SimpleAdapter(context,maps, R.layout.item_search_listview,new String[]{"name","number"}
                            ,new int[]{R.id.search_listview_text1, R.id.search_listview_text2}
                    );
                    listView.setAdapter(adapter);


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(context, list.size() + "下载错误", Toast.LENGTH_SHORT).show();
            }

        });
    }
}
